package com.banciyuan.bcywebview.biz.post.uploadpic;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.utils.encrypt.MD5;
import com.banciyuan.bcywebview.utils.file.FileTypeUtil;
import com.banciyuan.bcywebview.utils.file.FileUtils;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.sys.SystemUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Multi;

/**
 * Created by squall on 2016/1/4.
 */
public class UploadPicHelper {

    private static final String uploadFormat = "%s%s/%s.%s";
    private RequestQueue queue;
    private Context mContext;
    private IGetToken iGetToken;
    private String token;
    private boolean cancel = false;
    private boolean compress = false;

    public UploadPicHelper(Context mContext, IGetToken iGetToken, boolean compress) {
        this.mContext = mContext;
        this.iGetToken = iGetToken;
        this.compress = compress;
        queue = VolleyQueue.getRquest(mContext);
    }

    public void getToken(String tokenType, String id, String action, final List<PhotoModel> plist) {
        if (TextUtils.isEmpty(token)) {
            Response.Listener<String> onSuccToken = new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    if (StatusCodeUtils.dealStatusCode(s, mContext)) {
                        token = s;
                        if (!compress) {
                            orginThread(s, plist);
                        } else {
                            compPic(s, plist);
                        }
                    }
                }
            };

            Response.ErrorListener onError = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    iGetToken.getTokenFail();
                }
            };

            String url = HttpUtils.BASE_URL + action;
            List<BcyPair> paramsList = new ArrayList<>();
            paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(mContext).getToken()));
            if (!TextUtils.isEmpty(tokenType) && !TextUtils.isEmpty(id)) {
                paramsList.add(new BcyPair(tokenType, id));
            }
            HashMap<String, String> map = HttpUtils.getData(paramsList);
            StringRequestParam request = new StringRequestParam(Request.Method.POST, url, map, onSuccToken, onError);
            queue.add(request);
        } else {
            if (!compress) {
                orginThread(token, plist);
            } else {
                compPic(token, plist);
            }
        }
    }

    private void orginThread(final String response, final List<PhotoModel> plist) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                List<File> mFile = new ArrayList<File>();
                for (PhotoModel p : plist) {
                    if (!p.isUpload()) {
                        if (!TextUtils.isEmpty(p.getOriginalPath())) {
                            mFile.add(new File(p.getOriginalPath()));
                        }
                    }
                }
                if (!cancel) {
                    upLoadFile(response, mFile);
                }
            }
        });
    }

    private void compPic(final String response, final List<PhotoModel> plist) {

        new AsyncTask<Void, List<File>, List<File>>() {
            @Override
            protected List<File> doInBackground(Void... params) {
                List<File> mFile = new ArrayList<>();
                try {
                    for (PhotoModel p : plist) {
                        File source = new File(p.getOriginalPath());
                        String srcPath = p.getOriginalPath();
                        String name = MD5.getMD5(srcPath);
                        File file = new File(ImageManager.getTemp(mContext) + name);
                        mFile.add(file);
                        if (!new FileTypeUtil().getFileByFile(source).equals("gif")) {
                            int degree = ImageManager.readPictureDegree(srcPath);
                            BitmapFactory.Options newOpts = new BitmapFactory.Options();
                            newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
                            // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
                            newOpts.inJustDecodeBounds = true;
                            Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); // 此时返回bm为空
                            newOpts.inJustDecodeBounds = false;
                            // 现在主流手机比较多是1080p分辨率，所以高和宽我们设置为
                            float needWidth = 1080f;// 这里设置宽度为1080f
                            int be = 1;// be=1表示不缩放
                            be = (int) (newOpts.outWidth / needWidth);
                            if (be <= 0) be = 1;
                            newOpts.inSampleSize = be;// 设置缩放比例
                            // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
                            bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
                            ImageManager.saveTempImageifBig(mContext, bitmap, name, true, 1080f, 90, degree);
                        } else {
                            FileUtils.fileChannelCopy(source, file);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return mFile;
            }

            @Override
            protected void onPostExecute(List<File> files) {
                if (files.size() > 0) {
                    upLoadFile(response, files);
                } else {
                    iGetToken.getTokenFail();
                }
            }
        }.execute();

    }

    private void upLoadFile(String response, final List<File> mFile) {
        try {
            final List<Multi> upload = new ArrayList<>();
            JSONObject jsonResult = new JSONObject(response).getJSONObject("data");
            String mToken = jsonResult.getString("cloud_upToken");
            String mPrefix = jsonResult.getString("cloud_prefix");
            UploadManager uploadManager = new UploadManager();
            for (final File file : mFile) {
                uploadManager.put(file, getFilename(mPrefix, file), mToken, new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Multi multi = new Multi();
                        try {
                            if (info.isOK()) {
                                String path = response.getString("key");
                                int h = response.getInt("h");
                                int w = response.getInt("w");
                                multi.setPath(path);
                                multi.setH(h);
                                multi.setW(w);

                                multi.setLocal_path(file.getAbsolutePath());
                                multi.setUpdate_status(true);
                            } else {
                                multi.setLocal_path(file.getAbsolutePath());
                                multi.setUpdate_status(false);
                            }
                        } catch (JSONException e) {
                            multi.setLocal_path(file.getAbsolutePath());
                            multi.setUpdate_status(false);
                        } finally {
                            upload.add(multi);
                            if (upload.size() == mFile.size()) {
                                iGetToken.getTokenSucc(upload);
                                token = null;
                            }
                        }
                    }
                }, new UploadOptions(null, null, false, null, new UpCancellationSignal() {
                    @Override
                    public boolean isCancelled() {
                        return false;
                    }
                }));
            }
        } catch (JSONException e) {
            iGetToken.getTokenFail();
        }
    }

    private String getFilename(String mPrefix, File file) {
        String uniqueid = MD5.getUUID();
        String mDate = Integer.toString(Integer.parseInt(SystemUtils.getDateYmd()), 36);
        return String.format(uploadFormat, mPrefix, mDate, uniqueid, new FileTypeUtil().getFileByFile(file));
    }


    public void cancel() {
        this.cancel = true;
    }


}
